import sys
import os
import time
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import boto3
from config import *
from pyathena import connect
import json
from base_class.inspect_logging import print_to_log

def submit(sql):
    result = try_submit(sql)
    if result["statusCode"] == 500:
        for i in range(3):
            if result["statusCode"] == 500:
                    time.sleep(1)
                    result = try_submit(sql)
            else:
                break
    if result["statusCode"] == 500:
        print_to_log("sql执行失败")
        raise Exception("执行athena sql语句异常:"+str(result["msg"]))
    else:
        return result



def try_submit(sql):
    try:
        cursor = connect(s3_staging_dir=OutputLocation, region_name=FORMAL_S3_CONFIG['region_name'],
                         aws_access_key_id=FORMAL_S3_CONFIG['access_key'],
                         aws_secret_access_key=FORMAL_S3_CONFIG['secret_key']
                         ).cursor(schema_name=db)

        cursor.execute(sql)
        result = cursor.fetchall()
        return {
            'statusCode': 200,
            'body': json.dumps('success'),
            'msg': 'submit ok',
            'result': result
        }
    except Exception as e:
       return {
            'statusCode': 500,
            'body': json.dumps('error'),
            'msg': str(e)
        }


